
import {getCookieList,delCookie,getCookie,setCookie} from "../cookie/cookie.js";
layui.use(['table','layer'], function() {
        var table = layui.table,layer = layui.layer,form = layui.form;


        getCookie("jsonAndCookie") == "true"?$("#jsonAndCookie").prop("checked", true):$("#jsonAndCookie").prop("checked", false);
        form.render();

        jsonList(table);

        table.on('tool(dataTable)', function(obj) {
            var d = obj.data;
            if(obj.event === 'login') {
                let i;
                $.ajax({
                    url:'/login',
                    method:'post',
                    data:JSON.stringify(d),
                    dataType:'JSON',
                    contentType: "application/json; charset=utf-8",
                    beforeSend:function () {
                        i = layer.msg('连接中...', { icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, offset: '50%', time: 300000 });
                    },
                    success:function (res){
                        if (res.code == 200){
                            window.parent.skip();
                            layer.close(i);
                        }else if (res.code == 108){
                            layer.alert('session未过期 无需重复登录', {
                                time: 3*1000
                                ,success: function(layero, index){
                                    var timeNum = this.time/1000, setText = function(start){
                                        layer.title((start ? timeNum : --timeNum) + ' 秒后跳转', index);
                                    };
                                    setText(!0);
                                    this.timer = setInterval(setText, 1000);
                                    if(timeNum <= 0)clearInterval(this.timer);
                                }
                                ,end: function(){
                                    clearInterval(this.timer);
                                    window.parent.skip();
                                }
                            });
                        }else {
                            layer.close(i);
                            layer.msg(res.msg, {icon: 5});
                        }
                    }
                });
            }
            if (obj.event === 'del'){
                layer.confirm('确认要'+d.id+'删除吗？', function (index) {
                    getCookie("jsonAndCookie") == "true"?
                    $.get('/delLoginObj/'+d.id,{},function (res) {
                        jsonList(table);
                    }):delCookie(d.id);
                    layer.msg('已删除!', {icon: 1, time: 1000});
                    jsonList(table);
                });
            }
            if (obj.event === 'select'){
                layer.open({
                    type: 1,
                    title:"密码",
                    area: ['300px', '135px'],
                    content: '<div style="text-align: center;line-height: 30px;">打死也不告诉别人!<br/>密码:'+d.pwd+'</div>'
                });
            }
        });

        table.on('toolbar(dataTable)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data;

            if (obj.event === "exportData"){
                if (data.length === 0){
                    layer.msg("请勾选", {icon: 5});
                }else {
                    layer.prompt({title: '请输入保存的文件名（不需要加后缀）', formType: 0}, function(pass, index){
                        var eleLink = document.createElement('a');
                        eleLink.download = pass+'.json';
                        eleLink.style.display = 'none';
                        var blob = new Blob([JSON.stringify(data)]);
                        eleLink.href = URL.createObjectURL(blob);
                        document.body.appendChild(eleLink);
                        eleLink.click();
                        document.body.removeChild(eleLink);
                        layer.close(index);
                    });
                }
            }

        });

        $('#importData').change(function (e) {
            let f = e.target.files;
            for(var i=0;i<f.length;i++){
               var reader = new FileReader();
               reader.readAsDataURL(f[i]);
               reader.onload = function(e){
                   var base = new Base64();
                   let objStr = base.decode(e.target.result.split(',')[1]);
                   let objList = JSON.parse(objStr);
                   $.each(objList,function (index,item) {
                       setCookie(item.id,JSON.stringify(item),item.survivalTime);
                   })
                   jsonList(table);
               }
            }
        });

        //监听指定开关
        form.on('switch(jsonAndCookie)', function(data){
            setCookie("jsonAndCookie",this.checked,"d100")
            location.reload();
        });

        $('#help').click(function (){
            layer.alert("" +
                "1. 当前系统为两种存储方式，cookie存储，json存储，默认cookie，点击switch按钮切换不同方式存储" +
                "<br/>" +
                "2. cookie存储: 当前登录数据，以及在首页部分按钮数据会保存在您的网页cookie中" +
                "<br/>" +
                "3. 部分因浏览器不同，对cookie的个数，以及大小不同，所以是有限制性的" +
                "<br/>" +
                "4. json存储: json存储是添加的数据会发往后台，后台获取你的桌面路径后将json文件写入到你的桌面" +
                "<br/>" +
                "5. 每次窗体加载时回去读取桌面中的json文件内容，相对于json存储方式，没有限制性的，取决你的硬盘", {
                    title:'帮助'
            });
        });
  });

function tableReadr(table,dataList){
    table.render({
        elem:'#dataTable',
        toolbar: getCookie("jsonAndCookie") == "true"?'#toolbar2':'#toolbar',
        cols:[
            [
                {type: 'checkbox', fixed: 'left'},
                {field:'id',title:'ID',sort:true,width:220},
                {field: 'ftpHost',title:'IP地址',width:150},
                {field: 'port',title: '端口号',width:80},
                {field: 'userName',title: '用户名',width:80},
                {field: 'pwd',title: '密码',width:100,templet:function (d){
                        return "<a href='#' lay-event='select' >点击查看</a>"
                    }},
                {field: 'ftpType',title: '连接方式',width:100,templet:function (d){
                        return "<span>"+d.ftpType+"</span>"
                    }},
                {field: 'timedOut',title: '超时时间',width:90},
                {field: 'lastTime',title: '创建时间'},
                {field: 'survivalTime',title: '存活时间',width:90,templet:function (d){
                        return "<span>"+survivalTime(d.survivalTime)+"</span>";
                    }},
                {title: '操作',templet:function (d){
                        return '<button type="button" lay-event="login" class="layui-btn  layui-btn-xs layui-btn-normal">登录</button>'+
                            '<button type="button" lay-event="del" class="layui-btn layui-btn-xs  layui-btn-danger">删除</button>'
                    }}
            ]
        ],
        data:dataList==null?[]:dataList,
        even: true,
        page: true
    });
}

function survivalTime(survivalTime){
    if (survivalTime !== undefined && survivalTime.length >= 2){
        let time = survivalTime.replace('d','天').replace('h','时').replace('s','秒');
        let lastChar = time.substring(0,1);
        let firstChar = time.substring(1);
        return firstChar+lastChar;
    }
}

function jsonList(table){
    getCookie("jsonAndCookie") == "true"?
    $.get('/loginList',{},function (res) {
        tableReadr(table,res.data);
    }):tableReadr(table,getCookieList());
}